package com.wontube.smr.bo.sites.youtube;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wontube.client.extension.utils.StringUtils;
import com.wontube.core.pub.AppEnvironment;
import com.wontube.smr.bo.sites.youtube.IYouTubeService;
import com.wontube.smr.bo.sites.youtube.impl.CombineYouTubeService;


/**
 * @author yuechao
 * 
 */
public final class YouTubeFactory {
	private YouTubeFactory() {
	}

	private static final Logger logger = LoggerFactory.getLogger(YouTubeFactory.class);

	private static IYouTubeService prototype = new CombineYouTubeService();

	public static final void loadService(File file) {
		if (!file.exists()) {
			return;
		}

		InputStreamReader reader = null;

		try {
			reader = new InputStreamReader(new FileInputStream(file), AppEnvironment.charsetName);
			Gson gson = new Gson();
			Type type = new TypeToken<HashMap<String, String>>() {
			}.getType();
			Map<String, String> map = gson.fromJson(reader, type);

			String clazzName = map.get("serviceClass");
			if (!StringUtils.isNullOrEmpty(clazzName)) {
				Class<?> clazz = Class.forName(clazzName);
				IYouTubeService temp = (IYouTubeService) clazz.newInstance();
				YouTubeFactory.prototype = temp;

				logger.info("loaded youtube service class: {}", clazzName);
			}

		} catch (IOException e) {
			logger.error(e.toString());
		} catch (ClassNotFoundException e) {
			logger.error(e.toString());
		} catch (InstantiationException e) {
			logger.error(e.toString());
		} catch (IllegalAccessException e) {
			logger.error(e.toString());
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					logger.error(e.toString());
				}
			}
		}
	}

	public static IYouTubeService create() {
		return YouTubeFactory.prototype.createEmpty();
	}
}
